package com.mainbo.modular.system.controller;

import com.mainbo.core.util.FileUtil;
import com.mainbo.core.util.Result;
import com.mainbo.modular.system.model.PtResources;
import com.mainbo.modular.system.service.IPtResourcesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.UUID;

/**
 * @Author xww
 * @Description //TODO
 * @Date 2020/2/24   15:42
 **/
@Controller
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    private IPtResourcesService ptResourcesService;

    /**
     * upload file
     *
     * @param file
     *          file
     * @param relativePath
     *          save relative path
     * @param isWebRes
     *          is web resourse
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public void upload(
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "relativePath", required = false) String relativePath,
            @RequestParam(value = "isWebRes", required = false, defaultValue = "false") Boolean isWebRes,
            Writer writer) throws IOException {
        Result rs = new Result();
        rs.setCode(HttpStatus.BAD_REQUEST.value());
        if (file != null) {
            if (isWebRes) {
                PtResources res = ptResourcesService.saveWebResources(file, relativePath);
                if (res != null) {
                    rs.setData(res.getId());
                    rs.setCode(Result.SUCCESS);
                    rs.setMsg("上传成功！");
                }
            } else {
                PtResources res = ptResourcesService.saveTmptResources(file, relativePath);
                if (res != null) {
                    rs.setData(res.getId());
                    rs.setCode(Result.SUCCESS);
                    rs.setMsg("上传成功！");
                }
            }

        }

        if ("failed".equals(rs.getCode())) {
            rs.setMsg("上传失败！");
        }
        StringBuilder rb = new StringBuilder();
        rb.append("{\"code\":\"").append(rs.getCode()).append("\",\"data\":\"")
                .append(rs.getData()).append("\",\"msg\":\"")
                .append(new String(rs.getMsg().getBytes("UTF-8"), "ISO8859-1"))
                .append("\"}");

        writer.write(rb.toString());
    }

    /**
     * save resouces
     */
    @RequestMapping("/saveResource")
    @ResponseBody
    public Object saveResource(PtResources resources) {
        String id = UUID.randomUUID().toString().replaceAll("-","");
        String aimUrl = new StringBuilder(nullToEmpty(resources.getPath())).append(File.separator)
                .append(id).append(".").append(resources.getExt()).toString();
        resources.setPath(aimUrl);
        resources.setName(FileUtil.getFileName(resources.getName()));// 文件名，不含扩展名
        resources.setId(StringUtils.isEmpty(resources.getRmsResId()) ? id
                : resources.getRmsResId());
        resources.setState(PtResources.S_TEMP);
        resources.setDeviceName(FileUtil.CLOUD_DEVICE_NAME);
        resources.setCrtDttm(new Date());
         ptResourcesService.insert(resources);
        return resources;
    }
    public static String nullToEmpty(Object o) {
        return o == null ? "" : o.toString();
    }
}
